package com.hemi.rhet.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.util.Log;

import com.hemi.rhet.Constants;
import com.hemi.rhet.ParamUtil;

public class FileUtil {

	/**
	 * 附件上传到服务器
	 * 
	 * @param photoPath
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String uploadFile2Server(String photoPath)
			throws ClientProtocolException, IOException {
		HttpParams hps = new BasicHttpParams();
		hps.setParameter("userId", ApplicationContext.getData("userId"));
		HttpClient httpclient = new DefaultHttpClient();
		String urlStr = Constants.DOMAIN + Constants.file_upload_path;
		HttpPost httppost = new HttpPost(urlStr);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("filename", ("IMAGE.jpg")));
		File aFile = new File(photoPath);
		Log.i("info -- photoPath: ", photoPath);
		FileEntity fileEty = new FileEntity(aFile, "binary/octet-stream");
		if (fileEty != null && fileEty.getContentLength() > 0) {
			httppost.setEntity(fileEty);
			httppost.addHeader("filename", aFile.getName());
			httppost.addHeader("userInfo",
					"userId=" + ApplicationContext.getData("userId"));
			httppost.setParams(hps);
			HttpResponse response = httpclient.execute(httppost);
			Header[] headers = response.getAllHeaders();
			headers = response.getHeaders("resultMessage");
			String imageInfo = EntityUtils.toString(response.getEntity());
			HashMap mesg = ParamUtil.stringTomsgMap(imageInfo);
			if (mesg != null && mesg.get("resultcode").equals("0")) {
				return imageInfo;
			}

			httpclient.getConnectionManager().shutdown();

		}
		return "-1";
	}

	public static Bitmap getBitmapByFilePath(String filePath) {
		File image = new File(filePath);
		BitmapFactory.Options bounds = new BitmapFactory.Options();
		bounds.inJustDecodeBounds = true;
//		BitmapFactory.decodeFile(image.getPath(), bounds);
		if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
			return null;
//		int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
//				: bounds.outWidth;
		BitmapFactory.Options opts = new BitmapFactory.Options();
//		 opts.inSampleSize = originalSize / 2;
//		opts.inSampleSize = originalSize;
		return BitmapFactory.decodeFile(image.getPath(), opts);
	}

	/**
	 * 重置图片大小
	 * 
	 * @param bm
	 * @param newWidth
	 * @param newHeight
	 * @return
	 */
	public static Bitmap resizeBitmap(Bitmap bm, int newWidth, int newHeight) {
		// 图片源
		// Bitmap bm = BitmapFactory.decodeStream(getResources()
		// .openRawResource(id));
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		// 设置想要的大小
		int newWidth1 = newWidth;
		int newHeight1 = newHeight;
		// 计算缩放比例
		float scaleWidth = ((float) newWidth1) / width;
		float scaleHeight = ((float) newHeight1) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		bm.recycle();
		return newbm;

	}


	public static Bitmap getImageBitmapAndResetRotate(String bitmapUrl) throws IOException{
		Bitmap	bitmap=	getBitmapByFilePath(bitmapUrl) ;
		ExifInterface exifInterface = new ExifInterface(bitmapUrl);
		int tag = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
		int degree = 0;
		if (tag == ExifInterface.ORIENTATION_ROTATE_90) {
			degree = 90;
		} else if (tag == ExifInterface.ORIENTATION_ROTATE_180) {
			degree = 180;
		} else if (tag == ExifInterface.ORIENTATION_ROTATE_270) {
			degree = 270;
		}
		if (degree != 0 && bitmap != null) {
			 Matrix mtx = new Matrix();
			 mtx.preRotate(degree);
             bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2, mtx, false);
             bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

		}
		return bitmap;
	}
	
	
	public static Bitmap getImageBitmapAndSetRotate(String bitmapUrl,int degree) throws IOException{
		Bitmap	bitmap=	getBitmapByFilePath(bitmapUrl) ;
		
		


		
		if (degree != 0 && bitmap != null) {
			File aFile = new File(bitmapUrl);
			FileOutputStream	fOut = new FileOutputStream(aFile);
			Matrix mtx = new Matrix();
			mtx.preRotate(degree);
//			int w = bitmap.getWidth();
//			int h = bitmap.getHeight();
//			float sw = (float)428/w;
//			float sh = (float)570/h;
//			mtx.postScale(sw>1f?1f:sw, sh>1f?1f:sh);
//			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, false);
//			  mtx = new Matrix();
//			  mtx.preRotate(degree);
//			  bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, false);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, false);
//			bitmap=resizeBitmap(bitmap,428,570);
			int w = 428;
			int h = 570;
			if(bitmap.getWidth()<w)
			{
				w=bitmap.getWidth();
			}
			if(bitmap.getHeight()<h)
			{
				h = bitmap.getHeight();
			}
			bitmap = Bitmap.createScaledBitmap(bitmap, w, h, false);
			bitmap=getRoundedCornerBitmap(bitmap,0,degree);
//			Bitmap.c
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); 
		}
		return bitmap;
	}
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx,float degree){    
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);    
        Canvas canvas = new Canvas(output);    
        final int color = 0xff424242;    
        final Paint paint = new Paint();    
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());    
        final RectF rectF = new RectF(rect);    
        paint.setAntiAlias(true);    
        canvas.drawARGB(0, 0, 0, 0); 
//        Matrix mtx = new Matrix();
//		mtx.preRotate(degree);
//        canvas.setMatrix(mtx);
        
        paint.setColor(color);    
        paint.setTextSize(10);
        canvas.drawText("手机易航", bitmap.getWidth()-30, bitmap.getHeight()-15,paint);

        
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);    
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));    
        canvas.drawBitmap(bitmap, rect, rect, paint);    
      
        return output;    
    } 

	/**
	 * 获取远程图片
	 * 
	 * @param aURL
	 * @return
	 */
	public static Bitmap getRemoteImage(final URL aURL) {
		try {
			final URLConnection conn = aURL.openConnection();
			conn.connect();
			final BufferedInputStream bis = new BufferedInputStream(
					conn.getInputStream());
			  Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();
//			Bitmap bm2 = resizeBitmap(bm,80,80);
//			bm.recycle();
			return bm;
		} catch (IOException e) {
		}
		return null;
	}
	
	public static String  getUniqueId(){
		return new Date().getTime()+"";
	}

}
